<?php
namespace app\admin\controller;
use think\Loader;
use app\model\AdminUsers;
use app\model\Order;
class AdminController extends BackendController
{

    protected $adminUsers;

    protected function _initialize(){
        parent::_initialize();
        $this->adminUsers = new AdminUsers();
    }

    public function index()
    {
        $result = AdminUsers::field(['id','account','status','create_time'])->paginate(15);
        $this->assign('list',$result);
        return $this->fetch();
    }

    public function add(){
        if($this->request->isPost()){
            $data = [
                'account' => $this->request->post('account'),
                'password' => $this->request->post('password'),
            ];

            $validate = Loader::validate('User');

            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            $this->adminUsers->save($data)? $this->success('创建成功','admin/Admin/index') : $this->error($user->getError());
        }
        else{
            return $this->fetch();
        }
    }

    public function edit(){
        if($this->request->isPost()){
            if(!$this->request->has('id')){
                $this->error('编辑失败');  
            }
            $data = [
                'status' => $this->request->post('status'),
            ];
            // $data = [
            //     'password' => $this->request->param('password'),
            // ];
            // $rules = [
            //     'password' => 'require|length:4,20',
            // ];
            // $validate = new Validate($rules);
            // if(!$validate->check($data)){
            //     $this->error($validate->getError());
            // }
            $this->adminUsers->save($data,['id'=>$this->request->param('id')]) ? $this->success('编辑成功','admin/Admin/index'): $this->error($user->getError());
        }
        else{
            $result = AdminUsers::get($this->request->param('id'));
            $this->assign('user',$result);
            return $this->fetch();
        }
    }

    public function ban(){
        if($this->request->has('id')){
            $id = $this->request->param('id');
            $result = $this->adminUsers->save(['status'=>0],['id'=>$id]);
            $this->success('禁用成功');
        }else{
            $this->error('禁用失败');
        }
    }

}
